{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Deepest Node in a Binary Tree\n",
    "\n",
    "[The Original Question](https://mp.weixin.qq.com/s/xbznylZ3x1mLlQKTVAH0yw)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question\n",
    "\n",
    "You are given the root of a binary tree. Return the deepest node (the furthest node from the root)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Example\n",
    "\n",
    "```text\n",
    "    a\n",
    "   / \\\n",
    "  b   c\n",
    " /\n",
    "d\n",
    "```\n",
    "\n",
    "The deepest node in this tree is `d` at depth `3`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "class Node(object):\n",
    "    def __init__(self, val):\n",
    "        self.val = val\n",
    "        self.left = None\n",
    "        self.right = None\n",
    "\n",
    "    def __repr__(self):\n",
    "        # string representation\n",
    "        return self.val"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "def deepest(node):\n",
    "    if node is None:\n",
    "        return (node, 0)\n",
    "    elif node.left is None and node.right is None:\n",
    "        return (node, 1)\n",
    "    else:\n",
    "        left_subtree = deepest(node.left)\n",
    "        right_subtree = deepest(node.right)\n",
    "        if right_subtree[-1] > left_subtree[-1]:\n",
    "            return (right_subtree[0], right_subtree[-1] + 1)\n",
    "        else:\n",
    "            return (left_subtree[0], left_subtree[-1] + 1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(d, 3)\n"
     ]
    }
   ],
   "source": [
    "root = Node('a')\n",
    "root.left = Node('b')\n",
    "root.left.left = Node('d')\n",
    "root.right = Node('c')\n",
    "\n",
    "print(deepest(root))\n",
    "# (d, 3)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
